package com.vn.toaa.tintinscreenoff;

import java.util.Random;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;

import com.startapp.android.publish.StartAppAd;

public class ScreenService extends Service {
	
	public static final String TAG = ScreenService.class.getSimpleName();
	private ScreenReceiver mScreenReceiver;
	private StartAppAd mStartAppAd;
	private Handler mHandler = new Handler();
	private Random mRandom = new Random();

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		LogManager.debug(TAG, "onCreate");
		StartAppAd.init(getApplicationContext(), Constant.STARTAPP_DEVELOPER_ID, Constant.STARTAPP_APP_ID);
		mStartAppAd = new StartAppAd(getApplicationContext());
		
		mScreenReceiver = new ScreenReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_SCREEN_ON);
		intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mScreenReceiver, intentFilter);
	}
	
	@Override
	public void onDestroy() {
		if (mScreenReceiver != null) {
			unregisterReceiver(mScreenReceiver);
		}
		LogManager.debug(TAG, "onDestroy");
		super.onDestroy();
	}
	
	/**
	 * The Class ScreenReceiver.
	 */
	class ScreenReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
				// do nothing
			} else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
				LogManager.debug(TAG, "ACTION_SCREEN_ON");
				if (CommonUtils.isNetworkAvailable(getApplicationContext())) {
					if (mRandom.nextInt(11) <= 3) {
						mHandler.postDelayed(new Runnable() {
							public void run() {
								if (!PhoneCallReceiver.isPhoneCallProcessing()) {
									System.out.println("xxx: " + TAG);
									mStartAppAd.onResume();
									mStartAppAd.onBackPressed();
								}
							}
						}, 5000);
					}
				}
			}
		}
	}
}
